package com.dj.core.reg;

import java.util.Date;

import org.springframework.util.StringUtils;

import com.dj.core.user.api.MobileRegistedErrorException;
import com.dj.dal.ProfileDao;
import com.dj.dal.UserDao;
import com.dj.domain.entity.DaiJiaProfile;
import com.dj.domain.entity.DaiJiaUser;

/**
 * 类RegistService.java的实现描述：TODO 类实现描述
 * 
 * @author jasen.hsu.cn@gmail.com 2012-4-19 下午2:58:09
 */
public class RegistService {

    private UserDao    userDao;

    private ProfileDao profileDao;

    /**
     * 注册用户
     * 
     * @param daijiaUser
     */
    public void registUser(DaiJiaUser daijiaUser) throws MobileRegistedErrorException {
        Date now = new Date();
        daijiaUser.setGmtModified(now);
        daijiaUser.setGmtReg(now);
        daijiaUser.setLoginId(daijiaUser.getLoginId().toLowerCase());
        DaiJiaUser dbUser = null;
        if (StringUtils.hasLength(daijiaUser.getMobile())) {
            dbUser = userDao.getByMobileAndSite(daijiaUser.getMobile());
        }
        if (dbUser != null) {
            throw new MobileRegistedErrorException();
        }
        userDao.create(daijiaUser);
    }

    /**
     * 修改用户基础信息
     * 
     * @param daijiaUser
     */
    public void updateBasicInfo(DaiJiaUser daijiaUser) {
        DaiJiaUser dbUser = userDao.load(daijiaUser.getId());
        if (dbUser == null) {
            return;
        }
        dbUser.setCity(daijiaUser.getSex());
        dbUser.setCounty(daijiaUser.getCounty());
        dbUser.setName(daijiaUser.getName());
        dbUser.setProvince(daijiaUser.getProvince());
        dbUser.setSex(daijiaUser.getSex());
        userDao.update(dbUser);
    }

    /**
     * 保存用户附加信息
     * 
     * @param profile
     * @return
     */
    public DaiJiaProfile saveProfile(DaiJiaProfile profile) {
        DaiJiaProfile dbUserProfile = null;
        if (profile.getId() == null && profile.getUid() != null) {
            dbUserProfile = profileDao.loadByUid(profile.getUid());
        }
        if (dbUserProfile != null) {// 用户附加信息是否已存在，存在则更新
            profile.setId(dbUserProfile.getId());
        }
        profile.setGmtModified(new Date());
        if (profile.getId() != null) {
            profileDao.update(profile);
        } else {
            profileDao.create(profile);
        }
        return profile;
    }

    /**
     * 取得当前用户附加信息
     * 
     * @param uid
     * @return
     */
    public DaiJiaProfile getUserProfile(Long uid) {
        return profileDao.loadByUid(uid);
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void setProfileDao(ProfileDao profileDao) {
        this.profileDao = profileDao;
    }

}
